package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 * 
 * @author alexis
 * @date 2025-11-09
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto)
    {
        // 修改iot平台数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());

        UpdateDevice updatedevice = new UpdateDevice();
        updatedevice.setDeviceName(deviceDto.getDeviceName());
        request.withBody(updatedevice);
         client.updateDevice(request);
        // 修改 mysql数据
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
       return updateById(device) ?1:0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProducts() {

        // 访问iot平台
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        // 把数据存储到redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));


    }

    @Override
    public List<ProductVo> allProduct() {
        // 从redis 中获取数据
        String result = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_LIST);

        if(StringUtils.isEmpty(result)){
            return new ArrayList<ProductVo>();
        }

        List<ProductVo> list = JSONUtil.toList(result, ProductVo.class);
        return list;


    }

    @Override
    public void register(DeviceDto deviceDto) {
        // 判断 设备名称 和设备标记 是否已经存在
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceName,deviceDto.getDeviceName())
                .or().eq(Device::getNodeId,deviceDto.getNodeId());
        long count = count(wrapper);
        if(count >0){
            throw  new BaseException("设备名称或者设备标识码已经存在");
        }

        // 判断 统一位置是否已经绑定了 同产品的设备
        LambdaQueryWrapper<Device> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Device::getProductKey,deviceDto.getProductKey())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType());
        long count2 = count(wrapper2);
        if(count2>0){
            throw  new BaseException("该老人/位置 已经绑定过同产品的设备");
        }


        // 调用IOT平台接口 设备注册
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.withProductId(deviceDto.getProductKey());
        addDevice.withDeviceName(deviceDto.getDeviceName());
        addDevice.withNodeId(deviceDto.getNodeId());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-","");
        authInfo.withSecret(secret);
        addDevice.setAuthInfo(authInfo);
        request.withBody(addDevice);
        AddDeviceResponse response;
        try {
             response = client.addDevice(request);
        } catch (Exception e) {
           e.printStackTrace();
           throw new BaseException("调用IOT接口报错");
        }
        // 保存 设备数据 到mysql
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);
    }

    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        // 1. 查询mysql数据
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId,iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if(device == null){
            throw  new BaseException("查询的设备不存在");
        }
        //2. 查询iot平台
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(request);
        //3. 整合数据 返回
        DeviceDetailVo detailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,detailVo);
        // 设置设备状态
        detailVo.setDeviceStatus(showDeviceResponse.getStatus());
        // 获取激活时间
        String activeTimeStr = showDeviceResponse.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime=activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            detailVo.setActiveTime(activeTime);
        }
        return detailVo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        List<Map<String, Object>> result = new ArrayList<>();
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        List<DeviceShadowData> shadow = response.getShadow();
        // 判断是否获取到了影子数据
        if(CollUtil.isEmpty(shadow)){
            return  result;
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
          LocalDateTime eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        final LocalDateTime eventTime2=eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        jsonObject.forEach((k,v)->{
            HashMap<String, Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime2);
            result.add(map);
        });


        return result;
    }

    @Override
    public void deleteDeviceByIotId(String iotId) {

        // 删除IOT平台
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        client.deleteDevice(request);


        // 删除mysql
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId,iotId);
        remove(wrapper);

    }
}
